package com.zhanghe.chap01;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Test
 *   
 * @author Clevo  
 * @date 2017/12/26 0:14 
 */  
public class test {
	
	@org.junit.Test
	public void testUnSageSequance(){
		UnSafeSequance unSafeSequance = new UnSafeSequance();
		ExecutorService executorService = Executors.newFixedThreadPool(100);
		long starttime = System.currentTimeMillis(); 
		for(int i=0;i<10000;i++){
			executorService.execute(new testGetnextUnsafe(unSafeSequance));
		}
		
		executorService.shutdown();
		while(true){
    		if(executorService.isTerminated()){
    			break;
    		}
    		try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
			}
    	}
		long endtime = System.currentTimeMillis(); 
		System.out.println("线程不安全 执行之后value:"+unSafeSequance.getValue());
		System.out.println("线程不安全 执行耗时"+(endtime-starttime));
	}
	
	class testGetnextUnsafe implements Runnable{
		UnSafeSequance unSafeSequance;
		public testGetnextUnsafe(UnSafeSequance unSafeSequance){
			this.unSafeSequance = unSafeSequance;
		}
		
		@Override
		public void run() {
			unSafeSequance.getNext();
		}
		
	}
	
	
	@org.junit.Test
	public void testSafeSequance(){
		Sequance sequance = new Sequance();
		ExecutorService executorService = Executors.newFixedThreadPool(100);
		long starttime = System.currentTimeMillis(); 
		for(int i=0;i<10000;i++){
			executorService.execute(new testGetnextsafe(sequance));
		}
		
		executorService.shutdown();
		while(true){
    		if(executorService.isTerminated()){//
    			break;
    		}
    		try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
			}
    	}
		long endtime = System.currentTimeMillis(); 
		System.out.println("线程安全 执行之后value:"+sequance.getValue());
		System.out.println("线程安全 执行耗时"+(endtime-starttime));
	}
	
	class testGetnextsafe implements Runnable{
		Sequance sequance;
		public testGetnextsafe(Sequance sequance){
			this.sequance = sequance;
		}
		
		@Override
		public void run() {
			sequance.getNext();
		}
		
	}
}
